package com.realtyManage.springboot.Service.impl;

import com.realtyManage.springboot.Config.MyLog;
import com.realtyManage.springboot.Dao.*;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.RegEntity;
import com.realtyManage.springboot.Model.Vo.UserTaskEntity;
import com.realtyManage.springboot.Service.IApplyInfoService;
import com.realtyManage.springboot.Service.ICustomerRegistrationService;
import com.realtyManage.springboot.Service.IUserService;
import com.realtyManage.springboot.Service.IUserTaskService;
import com.realtyManage.springboot.Utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserTaskServiceImpl implements IUserTaskService {
    @Autowired
    private UserTaskRepository userTaskRepository;

    @Autowired
    private CustomerLevelTimeRepository customerLevelTimeRepository;

    @Autowired
    private ForwardRepository forwardRepository;

    @Autowired
    private ICustomerRegistrationService customerRegistrationService;

    @Autowired
    private IntegralRepository integralRepository;

    @Autowired
    private IUserService userService;

    @Autowired
    private IApplyInfoService applyInfoService;

    @Autowired
    private ApplyRuleRepository applyRuleRepository;

    @Override
    public UserTask findById(Integer userId) {
        return userTaskRepository.findById(userId).orElse(null);
    }

    @Override
    public int insert(UserTask userTask) {
        if (userTask.getId() == null){
            return userTaskRepository.saveAndFlush(userTask).getId();
        }else{
            return userTaskRepository.update(userTask);
        }
    }

    @Override
    public int update(UserTask userTask) {
        return userTaskRepository.update(userTask);
    }

    @MyLog(value = "查询任务列表")
    @Override
    public Page<UserTask> findPagedByWhereClause(UserTaskEntity userTaskEntity) {
        Integer pageNumber = userTaskEntity.getPageNumber()-1;
        Integer pageSize = userTaskEntity.getPageSize();
        //排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if(userTaskEntity.getSort() != null){
            if (userTaskEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, userTaskEntity.getSortField());
            } else if(userTaskEntity.getSort().equals("ASC")){
                sort = new Sort(Sort.Direction.ASC, userTaskEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);

        //动态查询条件
        Specification<UserTask> specification = (Specification<UserTask>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (userTaskEntity.getDistributionUserId()!=null) {
                // 根据角色查询
                Predicate p1 = criteriaBuilder.equal(root.get("distributionUserId"),userTaskEntity.getDistributionUserId());
                list.add(p1);
            }
            if (userTaskEntity.getType()!=null) {
                // 根据类型查询
                Predicate p2 = criteriaBuilder.equal(root.get("taskType"),userTaskEntity.getType() );
                list.add(p2);
            }
            Predicate p3 = criteriaBuilder.equal(root.get("isShow"),0 );
            list.add(p3);

            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return userTaskRepository.findAll(specification, pageable);
    }

    @MyLog(value = "删除任务")
    @Override
    public int deleteTask(String ids) {
        return userTaskRepository.deleteUserTaskById(ids);
    }

    @Override
    public CustomerLevelTime insertLevelTime(CustomerLevelTime customerLevelTime) {
        return customerLevelTimeRepository.saveAndFlush(customerLevelTime);
    }

    @Override
    public int deleteLevelTime(String ids) {
        return customerLevelTimeRepository.deleteLevelTime(ids);
    }

    @MyLog(value = "查询客户等级时间设置列表")
    @Override
    public Page<CustomerLevelTime> findPagedByWhereClause(RegEntity regEntity) {
        Integer pageNumber = regEntity.getPageNumber()-1;
        Integer pageSize = regEntity.getPageSize();
        //排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if(regEntity.getSort() != null){
            if (regEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, regEntity.getSortField());
            } else if(regEntity.getSort().equals("ASC")){
                sort = new Sort(Sort.Direction.ASC, regEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);

        //动态查询条件
        Specification<CustomerLevelTime> specification = (Specification<CustomerLevelTime>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return customerLevelTimeRepository.findAll(specification, pageable);
    }

    /**
     * 查询未成交的客户进入公池信息
     * @return
     */
    @Override
    public List<CustomerRegistration> teamCustomerRemind() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CustomerRegistration> z = null;
        Calendar calendar = Calendar.getInstance();
        List<CustomerRegistration> lst = new ArrayList<>();
        Integer A= null;
        Integer B= null;
        Integer C= null;
        Integer D= null;
        Integer E= null;
        //获取等级信息
        List<CustomerLevelTime> clt = customerLevelTimeRepository.findAll();
            for (int i = 0; i< clt.size();i++){
                if (clt.get(i).getLevel().equals("A")){
                    A = clt.get(i).getRemindTime();
                }else if (clt.get(i).getLevel().equals("B")){
                    B = clt.get(i).getRemindTime();
                }else if (clt.get(i).getLevel().equals("C")){
                    C = clt.get(i).getRemindTime();
                }else if (clt.get(i).getLevel().equals("D")){
                    D = clt.get(i).getRemindTime();
                }else if (clt.get(i).getLevel().equals("E")){
                    E = clt.get(i).getRemindTime();
                }
            }
            List<CustomerRegistration> crt = customerRegistrationService.getTeamCustomerList();
            if (crt != null){
            for(CustomerRegistration cr : crt){
                String level = cr.getLevel();
                calendar.setTime(cr.getComeTime());
                //推敲时间锉
                if(level != null){
                    if (level.equals("A")){
                        calendar.add(Calendar.DATE, +A);
                    }else if (level.equals("B")){
                        calendar.add(Calendar.DATE, +B);
                    }else if (level.equals("C")){
                        calendar.add(Calendar.DATE, +C);
                    }else if (level.equals("D")){
                        calendar.add(Calendar.DATE, +D);
                    }else if (level.equals("E")){
                        calendar.add(Calendar.DATE, +E);
                    }
                }
                    String s = sdf.format(new Date());
                    String e = sdf.format(calendar.getTime());
                    Long sy = DateUtils.between_days(s, e);
                    cr.setResidueDayNum(Math.toIntExact(sy));
            }
                Collections.sort(crt, new Comparator<CustomerRegistration>() {
                    @Override
                    public int compare(CustomerRegistration o1, CustomerRegistration o2) {
                        int i = o1.getResidueDayNum() - o2.getResidueDayNum();
                        return i;
                    }
                });
        }
        List<Integer> sxList = new ArrayList<Integer>();
        sxList.add(1);
        sxList.add(2);
        sxList.add(3);
        sxList.add(4);
        sxList.add(5);
        sxList.add(0);
        lst = crt.stream()
                .filter((CustomerRegistration c) -> sxList.contains(c.getResidueDayNum()))
                .collect(Collectors.toList());
        return lst;
    }

    @Override
    public List<CustomerRegistration> remindList(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CustomerRegistration> z = null;
        Calendar calendar = Calendar.getInstance();
        Integer A= null;
        Integer B= null;
        Integer C= null;
        Integer D= null;
        Integer E= null;
        //获取等级信息
        List<CustomerLevelTime> clt = customerLevelTimeRepository.findAll();
        for (int i = 0; i< clt.size();i++){
            if (clt.get(i).getLevel().equals("A")){
                A = clt.get(i).getRemindTime();
            }else if (clt.get(i).getLevel().equals("B")){
                B = clt.get(i).getRemindTime();
            }else if (clt.get(i).getLevel().equals("C")){
                C = clt.get(i).getRemindTime();
            }else if (clt.get(i).getLevel().equals("D")){
                D = clt.get(i).getRemindTime();
            }else if (clt.get(i).getLevel().equals("E")){
                E = clt.get(i).getRemindTime();
            }
        }
        List<CustomerRegistration> crt = customerRegistrationService.getTeamCustomerList();
        if (crt != null){
            for(CustomerRegistration cr : crt){
                String level = cr.getLevel();
                calendar.setTime(cr.getComeTime());
                //推敲时间锉
                if (level.equals("A")){
                    calendar.add(Calendar.DATE, +A);
                }else if (level.equals("B")){
                    calendar.add(Calendar.DATE, +B);
                }else if (level.equals("C")){
                    calendar.add(Calendar.DATE, +C);
                }else if (level.equals("D")){
                    calendar.add(Calendar.DATE, +D);
                }else if (level.equals("E")){
                    calendar.add(Calendar.DATE, +E);
                }
                String s = sdf.format(new Date());
                String e = sdf.format(calendar.getTime());
                Long sy = DateUtils.between_days(s, e);
                cr.setResidueDayNum(Math.toIntExact(sy));
            }
            Collections.sort(crt, new Comparator<CustomerRegistration>() {
                @Override
                public int compare(CustomerRegistration o1, CustomerRegistration o2) {
                    int i = o1.getResidueDayNum() - o2.getResidueDayNum();
                    return i;
                }
            });
        }
        return crt;
    }

    @Override
    public List<UserTask> queryMyTask(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return userTaskRepository.queryMyTask(userId,sdf.format(new Date()));
    }

    @Override
    public List<UserTask> queryFMyTask(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        System.out.println("shjijian=====>"+sdf.format(new Date()));
        return userTaskRepository.queryFMyTask(userId,sdf.format(new Date()));
    }

    @Override
    public int completeMyFTask(UserTask userTask) {
        return userTaskRepository.update(userTask);
    }

    @Override
    public List<String> completeMyTaskDetail(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List ids = new ArrayList();
        ids.add(userId);
        return userTaskRepository.completeMyTaskDetail(ids,sdf.format(new Date()));
    }

    @Override
    public void insertForward(Forward forward) {
        forwardRepository.save(forward);
    }


    public void updateCustomerTimeTasks(){
        CustomerRegistration customerRegistration = new CustomerRegistration();
        //获取用户等级跟新时间
        List<CustomerLevelTime> ta = customerLevelTimeRepository.findAll();
        Calendar cld = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0;i<ta.size();i++){
                Integer time = ta.get(i).getRemindTime();  //等级时间
                List<CustomerRegistration> cu = customerRegistrationService.findByLevel(ta.get(i).getLevel());
                //更新
                for (int j =0;j<cu.size();j++){
                   String y =  cu.get(j).getComeTime().toString(); //客户最新来访时间
                    cld.set(Calendar.YEAR, Integer.valueOf(y.substring(0,4)));
                    cld.set(Calendar.MONDAY,Integer.valueOf(y.substring(5,7)));
                    cld.set(Calendar.DATE,Integer.valueOf(y.substring(8,10)));
                    //调用Calendar类中的add()，增加时间量
                    cld.add(Calendar.DATE, time);
                    Date finalDate = cld.getTime();
                    if (sdf.format(finalDate).compareTo(sdf.format(new Date())) == -1){ //当前时间比对来访时间是否超过设置时间 -1代表过期
                        //修改进入公池信息
                        customerRegistration.setReceptionId(0);   //设置为0的无用户信息
                        customerRegistration.setReceptionName("0");
                        customerRegistration.setId(cu.get(j).getId());
                        customerRegistrationService.updatePublicPool(customerRegistration);
                    }
                }
        }
    }

    @Override
    public List<String> completeMyTaskDetailE(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List ids = new ArrayList();
        ids.add(userId);
        return userTaskRepository.completeMyTaskDetail(ids,sdf.format(new Date()));
    }

    @Override
    public List<String> myTaskDetail(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return integralRepository.getTaskE(userId,sdf.format(new Date()));
    }

    //注册用户进入公池
    public void updateInternetPublicUser(){
       //查询注册用户
        List<User> u = userService.findUser();
        if (u.size() > 0) {
            for (int i = 0; i < u.size(); i++) {
                CustomerRegistration c = new CustomerRegistration();
                //查询客户表是否存在此号码信息
                System.out.println("执行号码====》"+u.get(i).getTelephone());
                if (customerRegistrationService.findByPhone(u.get(i).getTelephone()) == null) {
                    //插入用户进入公池
                    System.out.println("公尺号码====》"+u.get(i).getTelephone());
                    c.setIsSystem(0);
                    c.setSex(u.get(i).getSex());
                    c.setReceptionId(0);
                    c.setReceptionName("0");
                    c.setLevel("E");
                    c.setPhone(u.get(i).getTelephone());
                    customerRegistrationService.saveInternetPublicUser(c);
                }
            }
        }
    }

    //删除非全号客户信息
    public void deleteFCustomer(){
        ApplyRule ar = applyRuleRepository.queryApplyRule();
        //获取保护天数
        int fqh = ar.getFqhNum();   //非全号保护期
        List<String> customer = customerRegistrationService.fCustomer();
        if (customer.size() > 0){
            for (int i =0;i<customer.size();i++){
                System.out.println("====虚拟号=======>"+customer.get(i));
                ApplyInfo ai = applyInfoService.queryApplyInfo(customer.get(i));
                if (ai != null){
                    Calendar ca = Calendar.getInstance();
                    Calendar xa = Calendar.getInstance();
                    xa.setTime(new Date());
                    ca.setTime(ai.getApplyTime());
                    ca.add(Calendar.DATE,fqh);// fqh为增加的天数，可以改变的
                    if(xa.compareTo(ca) > 0 ){
                        //进行删除操作
                        customerRegistrationService.deleteFCustomer(customer.get(i));
                    }
                 }
            }
        }
    }

    @Override
    public int yz(String time) {
        return userTaskRepository.yz(time);
    }
}
